/* eslint-disable @typescript-eslint/no-explicit-any */
// src/api/axios.ts
import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import type { RestResult } from './server-response';
import StoreManager from '@/plugins/storage';

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL, // 从环境变量获取基础 URL
  timeout: 5 * 60 * 1000, // 超时时间
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在这里可以添加请求头等操作，比如添加 token
    const token = StoreManager.getString("access-token");
    if (token && config.headers) {
      config.headers['access-token'] = `${token}`;
    }
    return config;
  },
  (error) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

const _resolveResponse = (response: AxiosResponse<any, any>) => {
  if (response.status !== 200) {
    return "服务请求异常！";
  }
  const { code, msg } = response.data;
  if (code !== 200) {
    ElMessage.error(msg);
    if (code === 401) {
      setTimeout(() => {
        StoreManager.clear();
        window.location.href = "/login";
      }, 100);
      return msg;
    }
  }
  return response.data;
}

export default {
  get<T>(url: string, data: any): Promise<RestResult<T>> {
    return new Promise((resolve, reject) => {
      service.request({ url: url, params: data, method: "GET" }).then((response) => {
        const result = _resolveResponse(response);
        if (typeof result === "string") {
          ElMessage.error(result);
          reject(result)
        } else {
          resolve({
            data: <T>response.data.data,
            totalCount: response.data.totalCount,
            code: response.data.code,
            msg: response.data.msg,
            success: response.data.code === 200
          })
        }
      })
    })
  },
  post<T>(url: string, data: any): Promise<RestResult<T>> {
    return new Promise((resolve, reject) => {
      service.request({ url: url, data: data, method: "POST" }).then((response) => {
        const result = _resolveResponse(response);
        if (typeof result === "string") {
          ElMessage.error(result);
          reject(result)
        } else {
          resolve({
            data: <T>response.data.data,
            totalCount: response.data.totalCount,
            code: response.data.code,
            msg: response.data.msg,
            success: response.data.code === 200
          })
        }
      })
    })

  }
};
